use crate::config::create_settings_service;
use reqwest::header::{HeaderMap, ACCEPT};
use reqwest::Client;
use serde_json::Value;

pub async fn get_base_url_utils() -> Vec<String> {
    let mut base_url_vec = Vec::new();
    let client = Client::new();
    let settings_service = create_settings_service();
    let server_address = match settings_service.get_setting("server_address") {
        Ok(Some(value)) => value,
        Ok(None) => {
            println!("Setting not found");
            return base_url_vec;
        }
        Err(e) => {
            println!("Error occurred: {}", e);
            return base_url_vec;
        }
    };
    let full_url = format!("{}/api/goods/base_url", server_address);

    // 设置请求头
    let mut headers = HeaderMap::new();
    headers.insert(
        ACCEPT,
        reqwest::header::HeaderValue::from_static("application/json"),
    );

    // 发送请求
    let response = match client.get(&full_url).headers(headers).send().await {
        Ok(response) => response,
        Err(err) => {
            eprintln!("Request error: {}", err);
            return base_url_vec;
        }
    };

    // 检查响应状态码
    if !response.status().is_success() {
        eprintln!("Failed to fetch data: {}", response.status());
        return base_url_vec;
    }

    // 解析 JSON 响应
    let json: Value = match response.json().await {
        Ok(json) => json,
        Err(err) => {
            eprintln!("Failed to parse JSON: {}", err);
            return base_url_vec;
        }
    };

    if let Value::Array(array) = json {
        for element in array {
            if let Value::String(s) = element {
                base_url_vec.push(s);
            } else {
                eprintln!("Response JSON element is not a string");
                break;
            }
        }
        // println!("Response JSON: {:?}", base_url_vec);
    } else {
        println!("Response JSON is not an array");
    }

    base_url_vec
}
